import React, { useEffect } from "react";
import http from "../../utils/http";
import { Form, Input, Button, Checkbox  } from "antd";
import useCountDown from "../../hooks/useCountDown";
import useDebounce from "../../hooks/useDebounce";
import { setUserInfo } from "../../reducers/userInfoSlice";
import { useDispatch } from "react-redux";

function Login() {
    const [form] = Form.useForm();
    const dis = useDispatch()

    const { count, startFn, isRun } = useCountDown( 5 )

    const getCode = () => {
      startFn()
      setTimeout(() => {
        const code = Math.random().toString(32).slice(2, 6);
        form.setFieldsValue({code: code})
      }, 3000)
    }
    const onFinish = useDebounce(async (values) => {
      const res = await http.post('/login', values)
      const {code, token} = res.data;

      if(code == 1) {
        // 存token
        localStorage.setItem('token', token)
        // 存用户名
        localStorage.setItem('username', values.username)
        // 存用户信息
        const userInfoRef = await http.get('/getUserInfo')
        const {data} = userInfoRef.data
        // 存redux
        dis(setUserInfo(data))
        if(values.remember) {
          localStorage.setItem('userpwd', JSON.stringify(values));
        }else{
          localStorage.removeItem('userpwd')
        }
        window.location.href = '/index/home'
      }
    }, 800);

    useEffect(() => {
      const userpwd = localStorage.getItem('userpwd')
      if(userpwd) {
        const {username, password} = JSON.parse(userpwd)
        form.setFieldsValue({username, password})
      }
    }, [])


    return (
        <div>
            <Form form={form} onFinish={onFinish}>
                <Form.Item
                    name="username"
                    label="用户名"
                    rules={[
                        { required: true, message: "请输入用户名，必填" },
                        { pattern: /^[a-z]{4,8}$/, message: "必须输入字母" },
                    ]}
                >
                    <Input placeholder="请输入用户名" />
                </Form.Item>
                <Form.Item
                    name="password"
                    label="密码"
                    rules={[
                        { required: true, message: "请输入用户名，必填" },
                        {
                            pattern: /^(?=.*[0-9])(?=.*[a-z])(?=.*[_]).{3,10}$/,
                            message: "必须输入字母数字下划线",
                        },
                    ]}
                >
                    <Input.Password placeholder="输入密码" />
                </Form.Item>

                <Form.Item label="验证码">
                    <Form.Item
                        name="code"
                        noStyle
                        rules={[
                            { required: true, message: "请输入用户名，必填" },
                            {
                                pattern: /^[0-9a-zA-Z]{4}$/,
                                message: "只能输入四位正确的验证码",
                            },
                        ]}
                    >
                        <Input
                            placeholder="输入验证码"
                            style={{ width: 200, marginRight: 10 }}
                        />
                    </Form.Item>
                    <Button disabled={isRun} onClick={getCode}>{ isRun ? count + '秒后重新获取' : '点击获取' }</Button>
                </Form.Item>

                <Form.Item name="remember" valuePropName="checked" label={null}>
                  <Checkbox>记住密码</Checkbox>
                </Form.Item>
                <Form.Item shouldUpdate>
                    {() => (
                        <Button
                            type="primary"
                            htmlType="submit"
                            disabled={
                              !form.isFieldsTouched(["username","password", "code"],true) ||
                                !!form
                                    .getFieldsError()
                                    .filter(({ errors }) => errors.length)
                                    .length
                            }
                        >
                            登录
                        </Button>
                    )}
                </Form.Item>
            </Form>
        </div>
    );
}

export default Login;